package com.supermarket.api.service.impl;

import com.supermarket.api.common.Constants;
import com.supermarket.api.common.PageParam;
import com.supermarket.api.entity.HotProductEntity;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.repository.HotProductRepository;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.service.HotProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人气推荐商品服务层
 * @author 李其伟
 * @date 2023/10/23
 */
@Slf4j
@Service
public class HotProductServiceImpl implements HotProductService {

    @Autowired
    private HotProductRepository hotProductRepository;
    @Autowired
    private ProductRepository productRepository;

    @Override
    public Page<ProductEntity> list(PageParam pageParam) {
        Sort sort = Sort.by(Sort.Direction.DESC, "sort");
        Pageable pageable = PageRequest.of(pageParam.getPageNum() , pageParam.getPageSize(), sort);
        Page<HotProductEntity> hotProductEntityPage = hotProductRepository.findAllByPublishStatus(Constants.PUBLISH_STATUS_UP,pageable);
        List<HotProductEntity> hotProductEntityList = hotProductEntityPage.getContent();

        //获取产品数据
        List<String> skuList = hotProductEntityList.stream().map(HotProductEntity::getSku).collect(Collectors.toList());
        List<ProductEntity> productEntityList = productRepository.findAllBySkuIn(skuList);
        Map<String,ProductEntity> map = productEntityList.stream().collect(Collectors.toMap(ProductEntity::getSku, entity ->entity));

        //设置列表
        List<ProductEntity> productList = new ArrayList<>();
        for(HotProductEntity entity : hotProductEntityList){
            productList.add(map.get(entity.getSku()));
        }

        //重新创建
        return new PageImpl<>(productList,hotProductEntityPage.getPageable(),hotProductEntityPage.getTotalElements());

    }

    @Override
    public List<ProductEntity> topList(Integer number) {
        PageParam pageParam = new PageParam();
        pageParam.setPageSize(number);
        Page<ProductEntity> page = this.list(pageParam);
        return page.getContent();
    }

}
